Crate csp

source ·
Expand description

This crate is a helper to quickly construct a CSP and then turn it into a String.

This library can help you when you don’t want to remember some weird formatting rules of CSP, and want to avoid typos. And it certainly can be handy if you need to re-use things, for example a list of sources (just .clone() them everywhere and you’re good to go!).

WARNING: this library does not care if you create invalid CSP rules, and happily allows them and turns them into Strings. But it does force you to use a typed structure, so it’ll be harder to mess up than when manually writing CSP. Another thing that this crate does not do: It does not do any base64 or percent encoding or anything like that.

Example usage

use csp::{CSP, Directive, Sources, Source};

let csp = CSP::new()
  .push(Directive::ImgSrc(
    Sources::new_with(Source::Self_)
      .push(Source::Host("https://*.example.org"))
      .push(Source::Host("https://shields.io")),
  ))
  .push(Directive::ConnectSrc(
    Sources::new()
      .push(Source::Host("http://crates.io"))
      .push(Source::Scheme("https"))
      .push(Source::Self_),
  ))
  .push(Directive::StyleSrc(
    Sources::new_with(Source::Self_).push(Source::UnsafeInline),
  ))
  .push(Directive::ObjectSrc(Sources::new()));

let csp_header = "Content-Security-Policy: ".to_owned() + &csp.to_string();

Most of the comments for various CSP things are from MDN, so they licensed under CC-BY-SA 2.5 So attribution of most of the docs goes to Mozilla Contributors.

Please go to MDN to read up to date docs, as these ones might not be up to date.

Structs

Enums

  • A CSP directive.
  • Optionally used for the Sandbox directive. Not using it but using the sandbox directive disallows everything that you could allow with the optional values.
  • The source that a bunch of directives can have multiple of.
  • Used for RequireSriFor Directive.